package com.rimi.util;

import com.alibaba.fastjson.JSONObject;
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.rimi.model.dto.LoginDto;

import java.text.ParseException;
import java.util.Date;

/**
 * @Author luc
 * @Date 2021/7/2
 */
public class JwtUtil {

    private static  String key = "adsfsadfsdaffgfdsafsadfwdsafsdajkh";

    //　加密
    public static String encode(Object data) throws JOSEException {

        // 创建基于HS256加密算法的header
        JWSHeader jwsHeader = new JWSHeader(JWSAlgorithm.HS256);

        // 创建PayLoad数据载体
        Payload payload = new Payload(JSONObject.toJSONString(data));

        // 创建JWS签名对象,绑定密钥
        JWSSigner signer = new MACSigner(key);

        // 创建JWS对象
        JWSObject jwsObject = new JWSObject(jwsHeader,payload);

        // 对JWS对象进行签名
        jwsObject.sign(signer);
        return jwsObject.serialize();

    }

    public static <T> T decode(Class<T> clazz, String decode) throws JOSEException, ParseException {

        // 解析加密的字符串
        JWSObject parse = JWSObject.parse(decode);
        // 被加密的载体
        Payload payload = parse.getPayload();

        // 创建验签对象
        MACVerifier macVerifier = new MACVerifier(key);
        // 验证签名
        if(parse.verify(macVerifier)) {
            // 验证签名成功

            // 以json字符串获取数据
            String string = payload.toString();
            // 将json字符串转换成java对象
            return JSONObject.parseObject(string,clazz);
        }
        throw new JOSEException("验签失败");

    }

    public static void main(String[] args) throws JOSEException, ParseException {

    }
}
